<?php

/**
 * Generovani playlistu na zaklade oblibenych ci casto poslouchanych skladeb
 */

class Playlist_Generator_Ultimate implements Playlist_GeneratorInterface
{
    /**
     *
     * @var string
     */

    private $_name;

    /**
     *
     * @var LastFM_User
     */

    private $_user;

    /**
     *
     * @var integer
     */

    private $_limit = 20;

    /**
     *
     * @param string $name
     */

    public function setName($name)
    {
        $this->_name = $name;
    }

    /**
     *
     * @return string
     */

    public function getName()
    {
        return $this->_name;
    }

    /**
     *
     * @param integer $limit
     */

    public function setLimit($limit)
    {
        $this->_limit = $limit;
    }

    /**
     *
     * @return integer
     */

    public function getLimit()
    {
        return $this->_limit;
    }

    /**
     *
     * @param LastFM_User $user
     */

    public function setUser(LastFM_User $user)
    {
        $this->_user = $user;
    }

    /**
     *
     * @return LastFM_User
     */

    public function getUser()
    {
        return $this->_user;
    }

    /**
     *
     * @return Playlist
     */

    public function getPlaylist()
    {
        $tracks = array();

        $i = 0;

        $this->_limit = 100;

        // seznam skladeb oblibenych skladeb
        $loved_tracks = $this->_user->getLovedTracks();

        if (!empty($loved_tracks->track))
        {
            foreach ($loved_tracks->track as $track)
            {
                $tracks[] = new Track((string)$track->name, (string)$track->artist->name);
            }
        }

        // v pripade nenaplneni limitu se pouziji i nejcasteji poslouchane skladby
        if (count($tracks) < $this->_limit)
        {
            $top_tracks = $this->_user->getTopTracks();

            foreach ($top_tracks->track as $track)
            {
                $tracks[] = new Track((string)$track->name, (string)$track->artist->name);
            }
        }

        // zamichani seznamu skladeb
        shuffle($tracks);

        // nasledne se odeberou nadlimitni skladby
        $count = count($tracks);

        for ($i = 0; $i < $count; $i++)
        {
            if ($i >= $this->_limit)
            {
                unset($tracks[$i]);
            }
        }

        return new Playlist($this->getName(), $tracks);
    }
}